package start.spring.basic.dynamic;


import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;

/**
 * 动态kafka操作类
 */
@Component
public class DynamicKafkaDAO {

    @Autowired
    DynamicKafkaRegister kafkaRegister;
    
    private KafkaTemplate<String, String> getKafka(String kafkaId) {
        return kafkaRegister.getKafkaTemplate(kafkaId);
    }
    
    public boolean kafkaExsit(String kafkaId) {
    	return kafkaRegister.kafkaExsit(kafkaId);
    }

    /**
     * 发送普通消息
     *
     * @param kafkaId
     * @param topic
     * @param data
     * @return
     */
    public ListenableFuture<SendResult<String, String>> send(String kafkaId, String topic, String data) {
        return getKafka(kafkaId).send(topic, data);
    }

    /**
     * 发送普通消息
     *
     * @param kafkaId
     * @param topic
     * @param key
     * @param data
     * @return
     */
    public ListenableFuture<SendResult<String, String>> send(String kafkaId, String topic, String key, String data) {
        return getKafka(kafkaId).send(topic, key, data);
    }


    /**
     * 发送普通消息
     *
     * @param kafkaId
     * @param topic
     * @param partition
     * @param key
     * @param data
     * @return
     */
    public ListenableFuture<SendResult<String, String>> send(String kafkaId, String topic, Integer partition, String key, String data) {
        return getKafka(kafkaId).send(topic, partition, key, data);
    }

    /**
     * 发送普通消息
     *
     * @param kafkaId
     * @param topic
     * @param partition
     * @param key
     * @param data
     * @return
     */
    public ListenableFuture<SendResult<String, String>> send(String kafkaId, String topic, Integer partition, Long timestamp, String key, String data) {
        ProducerRecord<String, String> producerRecord = new ProducerRecord<>(topic, partition, timestamp, key, data);
        return getKafka(kafkaId).send(producerRecord);
    }
}
